﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;

namespace Domotica.Gazing
{
    internal class GazeClicker
    {
        public GazeClicker(Gaze gaze, Config config)
        {
            _Gaze = gaze;
            _Config = config;
        }

        private readonly Gaze _Gaze;
        private readonly Config _Config;
        private DateTime _LastMove;
        private PointF _MouseClickRefPos;
        private int _LastElapsed;

        public void CheckClicker()
        {
            Point currentMousePos = _Gaze.Position;
            float r = _Config.MouseClickRadius;
            if (!WithinRadius(currentMousePos, _MouseClickRefPos, r))
            {
                _LastMove = DateTime.Now;
                _MouseClickRefPos = currentMousePos;
                _Gaze.OnGazeClickElapsedChanged(new GazeClickElapsedEventArgs(_Gaze, 0));
            }
            else if ((Elapsed()) >= _Config.MouseClickDwell)
            {
                _LastMove = DateTime.Now;
                if (_Config.MouseClicks)
                {
                    _Gaze.OnGazeClick(new GazeClickEventArgs(_Gaze));
                }
                _Gaze.OnGazeClickElapsedChanged(new GazeClickElapsedEventArgs(_Gaze, _Config.MouseClickDwell));
            }
            else
            {
                int elapsed = Elapsed();
                if (elapsed != _LastElapsed)
                {
                    _LastElapsed = elapsed;
                    _Gaze.OnGazeClickElapsedChanged(new GazeClickElapsedEventArgs(_Gaze, elapsed));
                }
            }
        }

        private int Elapsed()
        {
            return (int)(DateTime.Now - _LastMove).TotalMilliseconds;
        }

        private static bool WithinRadius(PointF center, PointF p, float r)
        {
            float num = center.X - p.X;
            float num2 = center.Y - p.Y;
            var num3 = (float)Math.Sqrt(((num * num) + (num2 * num2)));
            return (num3 < r);
        }
    }
}
